package com.yunji.common.utils;

import com.alibaba.fastjson2.JSONObject;
import com.yunji.common.constant.HTTPStatus;
import com.yunji.common.exception.ServiceException;
import com.yunji.common.utils.bean.BeanUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.AlgorithmParameters;
import java.security.Security;
import java.util.Arrays;
import java.util.Base64;

/**
 * @Package com.yunji.common.utils
 * FileName:	SecurityTools.java
 * Copyright:	Copyright © 2024 云集互联 All Rights Reserved
 * Company:		云集互联
 * @version: 1.0
 * @since: JDK 1.8.0_202
 * Create at:   2024-04-07 00:04:06
 * Description:
 * <p>
 * Modification History:
 * Author					Date					Version         Description
 * -------------------------------------------------------------------------------------
 * HuaAo0803@163.com	2024-04-07 00:04:06     1.0             1.0 Version
 */
public class SecurityTools {
    private static final Logger logs = LoggerFactory.getLogger(SecurityTools.class);

    private SecurityTools() {
        throw new IllegalStateException("SecurityTools class");
    }

    private static final String AES_NAME = "AES";

    private static final String AES_CIPHER = "AES/CBC/PKCS7Padding";

    public static JSONObject decryptAes(String data, String keys, String offset) {
        logs.info("解密数据{},解密密钥:{},数据偏移量:{}", data, keys, offset);

        // 被加密的数据
        byte[] dataByte = Base64.getDecoder().decode(data);
        // 加密秘钥
        byte[] keysByte = Base64.getDecoder().decode(keys);
        // 偏移量
        byte[] offsetByte = Base64.getDecoder().decode(offset);
        try {
            // 如果密钥不足16位，那么就补足.  这个if 中的内容很重要
            int base = 16;
            if (keysByte.length % base != 0) {
                int groups = keysByte.length / base + 1;
                byte[] temp = new byte[groups * base];
                Arrays.fill(temp, (byte) 0);
                System.arraycopy(keysByte, 0, temp, 0, keysByte.length);
                keysByte = temp;
            }

            // 初始化
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance(AES_CIPHER);
            SecretKeySpec spec = new SecretKeySpec(keysByte, AES_NAME);
            AlgorithmParameters parameters = AlgorithmParameters.getInstance(AES_NAME);
            parameters.init(new IvParameterSpec(offsetByte));
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化

            byte[] resultByte = cipher.doFinal(dataByte);
            if (BeanUtils.isNotNull(resultByte)) {
                String result = new String(resultByte, StandardCharsets.UTF_8);
                return JSONObject.parseObject(result);
            }
        } catch (Exception e) {
            logs.error("解密异常:", e);
            throw new ServiceException(HTTPStatus.BUSINESS, "解密异常");
        }
        return new JSONObject();
    }
}
